<template>
  <view class="app-layout">
    <app-header title="选择优惠券" />
    <view class="app-main">
      <view class="goods-container">
        <!-- 搜索区域（不变） -->
        <view class="order-search">
          <view v-for="(tab, index) in tabType" :key="index" class="type-item"
            :class="{ activeType: currentTabType == index }" @click="handlecurrentTabType(index)">
            {{ tab }}
          </view>
          <view style="flex: 1;margin-right: 10px;">
            <uni-data-select v-model="pageInfo.parentId" placeholder="请选择优惠券类型" :localdata="couponList"
              class="search-select"></uni-data-select>
          </view>
          <uni-datetime-picker v-model="range" type="daterange" @maskClick="maskClick" @change="handleTime"
            class="search-date" />
          <u-search placeholder="请输入商品ID/名称" v-model="pageInfo.keyword" clearable bgColor="#fff" borderColor="#e5e5e5"
            :showAction="false" @search="handleSearch" @clear="handleClose" class="search-input"
            :input-class="pageInfo.keyword ? 'search-input-active' : ''"></u-search>
          <u-button type="primary" text="搜索" @click="handleSearch" class="search-btn"></u-button>
          <u-button :plain="true" text="重置" @click="handleReset"></u-button>
        </view>

        <!-- 表格区域：uView Checkbox 组合实现 -->
        <view style="flex: 1; overflow: hidden;">
          <scroll-view scroll-y="true" style="height: 100%">
            <view class="form-container">
              <uni-table border stripe :loading="loading" emptyText="暂无更多数据">
                <u-checkbox-group v-model="selectedNames" @change="handleGroupChange">
                  <!-- 表头：明确7列（全选 + 6个数据列） -->
                  <uni-tr>
                    <uni-th width="50" align="center">
                      <u-checkbox-group @change="handleSelectAll" v-model="isAllSelected">
                        <u-checkbox name="all" size="20" active-color="#0F90FD"></u-checkbox>
                      </u-checkbox-group>
                    </uni-th>
                    <uni-th width="80" align="left">优惠券ID</uni-th>
                    <uni-th width="120" align="left">优惠券名称</uni-th>
                    <uni-th width="120" align="left">优惠券类型</uni-th>
                    <uni-th width="150" align="left">适用场景</uni-th>
                    <uni-th width="320" align="left">使用时间</uni-th>
                    <uni-th width="120" align="left">优惠券状态</uni-th>
                  </uni-tr>

                  <!-- 表格内容：u-checkbox-group 包裹，每行7列与表头对齐 -->

                  <uni-tr v-for="(row, rIndex) in tableData" :key="rIndex">
                    <!-- 第1列：u-checkbox（全选对应的行选择框） -->
                    <uni-td align="center" width="50">
                      <u-checkbox :name="row.a" shape="square" activeColor="#0f90fd" size="20"></u-checkbox>
                    </uni-td>
                    <!-- 第2-7列：数据列 -->
                    <uni-td width="80"><text> {{row.a}}</text></uni-td>
                    <uni-td width="120"><text>{{row.b}}</text></uni-td>
                    <uni-td width="120"><text>{{row.c}}</text></uni-td>
                    <uni-td width="150"><text>{{row.d}}</text></uni-td>
                    <uni-td width="320"><text>{{row.e}}</text></uni-td>
                    <uni-td width="120"><text>{{row.f}}</text></uni-td>
                  </uni-tr>
                </u-checkbox-group>
              </uni-table>
            </view>
          </scroll-view>
        </view>

        <!-- 底部按钮（不变） -->
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close">取消</button>
            <button class="submit_btn" @click="submit">确定</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    ref,
    reactive,
    watch
  } from 'vue'
  import {
    onLoad,
  } from '@dcloudio/uni-app'

  let tableData = ref([{
      a: "1",
      b: "优惠券名称1 ",
      c: "立减券 ",
      d: "门店自提/外卖配送",
      e: "2025-08-08 00:00:00 ~ 2025-08-10 23:59:59",
      f: "进行中"
    },
    {
      a: "2",
      b: "优惠券名称2 ",
      c: "满减券 ",
      d: "外卖配送",
      e: "2025-08-09 00:00:00 ~ 2025-08-15 23:59:59",
      f: "进行中"
    },
    {
      a: "3",
      b: "优惠券名称3 ",
      c: "折扣券 ",
      d: "门店自提",
      e: "2025-08-10 00:00:00 ~ 2025-08-20 23:59:59",
      f: "未开始"
    }
  ])

  let couponList = ref([{
    "value": 0,
    "text": "满减券"
  }, {
    "value": 1,
    "text": "立减券"
  }])
  let pageInfo = reactive({
    keyword: "",
    status: undefined,
    startDate: undefined,
    endDate: undefined,
    parentId: undefined
  })
  let range = ref([]),
    currentTabType = ref(0),
    tabType = ref(['进行中', '未开始']),
    loading = ref(true)

  const selectedNames = ref([])
  const isAllSelected = ref([])

  // 页面加载：初始化
  onLoad((e) => {
    loading.value = false
    if (e.couponId) {
      console.log( e.couponId,' e.couponId')
      selectedNames.value = e.couponId.split(",")
      isAllSelected.value = selectedNames.value.length === tableData.value.length ? ['all'] : [];
    }
  })


  const handleSelectAll = (ev) => {
    if (!ev.length) {
      selectedNames.value = []
    } else {
      selectedNames.value = tableData.value.map(row => row.a)
    }
  }


  const handleGroupChange = (ev) => {
    if (ev.length === tableData.value.length) {
      isAllSelected.value = ['all']
    } else {
      isAllSelected.value = []
    }
  }

  const handleTime = (e) => {
    if (e.length > 0) {
      pageInfo.startDate = e[0] + ' 00:00:00'
      pageInfo.endDate = e[1] + ' 23:59:59'
    } else {
      pageInfo.startDate = undefined
      pageInfo.endDate = undefined
    }
  }

  const handleSearch = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1
    // getData()
  }


  const handleReset = () => {
    pageInfo.keyword = '';
    pageInfo.startDate = undefined;
    pageInfo.endDate = undefined;
    pageInfo.parentId = undefined
    range.value = []
    // getData()
  }

  const handlecurrentTabType = (index) => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    currentTabType.value = index
    // getData()
  }

  // 提交：传递选中数据到上一页
  const submit = () => {
    if (selectedNames.value.length === 0) {
      return uni.showToast({
        title: '请选择优惠券',
        icon: 'none',
        duration: 2000
      })
    }
    const filteredArray = tableData.value.filter(row => selectedNames.value.includes(row.a));
    // const pages = getCurrentPages();
    // const prevPage = pages[pages.length - 2]
    // if (prevPage.handleReceiveCoupons) {
    //   prevPage.handleReceiveCoupons(filteredArray);
    //   console.log('已传递优惠券数据：', filteredArray);
    // } else {
    //   console.error('上一页面未找到 handleReceiveCoupons 方法');
    // }
     uni.$emit('receive-selected-coupons', filteredArray);
    setTimeout(() => uni.navigateBack(), 300)
  }

  const close = () => uni.navigateBack()
  const maskClick = () => {}
</script>
<style lang="scss" scoped>
  :deep(.is-disabled) {
    color: #333 !important;
  }

  :deep(.u-input) {
    background: #fff !important;
  }

  .form-container {
    padding: 0 20px;
    box-sizing: border-box;
  }

  .goods-container {
    background: #ffffff;
    border-radius: 10px;
    margin: 10px 10px 0;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    width: 100%;

    .order-search {
      display: flex;
      margin: 14px 20px;
      box-sizing: border-box;
      align-items: center;

      :deep(button) {
        width: 74px;
        height: 38px;
        margin-left: 11px;
        border-radius: 100px;
      }

      :deep(.uni-date) {
        margin-right: 10px;
      }

      :deep(.icon-calendar) {
        margin-left: 10px !important;
      }

      :deep(.u-search) {
        .u-search__content__input {
          height: 35px !important;
          line-height: 35px !important;
          display: block;
        }

      }

      // :deep(.uni-date__x-input) {
      //   height: 32px !important;
      //   line-height: 32px !important;
      // }

      // :deep(.range-separator) {
      //   height: 32px !important;
      //   line-height: 32px !important;
      // }

      :deep(.uni-date-x--border) {
        border-radius: 100px !important;
      }

      :deep(.uni-date-x) {
        border-radius: 100px !important;
      }

      :deep(.uni-select) {
        border-radius: 100px !important;
      }

      .type-item {
        font-weight: 400;
        font-size: 14px;
        color: #666666;
        display: flex;
        align-items: center;
        background: #f6f6f6;
        padding: 7px 12px;
        box-sizing: border-box;
        border-radius: 10px;
        margin-right: 10px;
      }

      .activeType {
        background: rgba(15, 144, 253, 0.1);
        color: #0f90fd;
      }
    }


  }
</style>
